import Taro, { request } from '@tarojs/taro'
const baseUrl = process.env.TARO_APP_BASE_URL


const requestApi = (options: any) => {
  return new Promise((resolve, reject) => {
    const headers = {
      Accept: '*/*',
      'tenant-id': 1,
      terminal: 10,
      'Content-Type': 'application/json',
      platform: 'WechatMiniProgram',
      ...options?.header,
      Authorization: `Bearer ${Taro.getStorageSync('token')}`, // 添加 token
    };

    // 检查是否有 filePath 和 name，如果是上传文件
    if (options?.filePath && options?.name) {
      // 上传文件流
      request({
        ...options,
        url: baseUrl + options.url,
        method: 'POST', // 上传文件通常使用 POST 方法
        header: headers,
        timeout: 60000, // 60秒超时
        // formData: {
        //   ...options.data, // 其他需要上传的数据
        // },
        filePath: options.filePath, // 文件路径
        name: options.name, // 表单中字段的名称
        
      }).then(
        (response) => {
          resolve(response?.data ?? response)
        },
        (err) => {
          reject(err)
        }
      );
    } else {
      // 正常的请求处理
      request({
        ...options,
        header: headers,
        url: baseUrl + options.url,
      }).then(
        (response) => {
          resolve(response?.data ?? response)
        },
        (err) => {
          reject(err)
        }
      );
    }
  });
}
const safeRequest = (apiPath: string, options: any) => {
  return new Promise((resolve, reject) => {
    request({
      method: 'GET',
      ...options,
      header: {
        Accept: 'text/json',
        'Content-Type': 'application/json;charset=UTF-8',
        platform: 'WechatMiniProgram',
        ...options?.header,
      },
      url: baseUrl + apiPath,
    }).then(
      (response) => {
        resolve(response?.data ?? response)
      },
      (err) => {
        reject(err)
      }
    )
  })
}

/**
 * get
 * @param url
 * @param opts
 * @returns {Promise}
 */
const get = async (url: string, opts: any): Promise<any> => {
  return safeRequest(url, opts)
}

/**
 * post
 * @param url
 * @param opts
 * @returns {Promise}
 */
const post = async (url: string, opts: any): Promise<any> => {
  return safeRequest(url, {
    ...opts,
    method: 'POST',
  })
}

/**
 * put
 * @param url
 * @param opts
 * @returns {Promise}
 */
const put = async (url: string, opts: any): Promise<any> => {
  return safeRequest(url, {
    ...opts,
    method: 'PUT',
  })
}

export  {
  requestApi,
  get,
  post,
  put,
}
